package com.zone.mybatis.executor;

import com.zone.mybatis.executor.resultset.ResultSetHandler;
import com.zone.mybatis.executor.statement.StatementHandler;
import com.zone.mybatis.mapping.BoundSql;
import com.zone.mybatis.mapping.Environment;
import com.zone.mybatis.mapping.MappedStatement;
import com.zone.mybatis.session.Configuration;
import com.zone.mybatis.transaction.Transaction;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

/**
 * @author: zongzi
 * @description: TODO
 * @date: 2024/1/1
 */
public class SimpleExecutor extends BaseExecutor {

    public SimpleExecutor(Configuration configuration, Transaction transaction) {
        super(configuration, transaction);
    }

    @Override
    public <T> List<T> doQuery(MappedStatement ms, Object paramObject) {
        Configuration configuration = super.getConfiguration();
        BoundSql boundSql = ms.getBoundSql();
        ResultSetHandler resultSetHandler = configuration.getResultSetHandler(boundSql);
        StatementHandler statementHandler = configuration.getStatementHandler(boundSql, paramObject, resultSetHandler);

        try {
            Environment environment = configuration.getEnvironment();
            DataSource dataSource = environment.getDataSource();
            Connection connection = dataSource.getConnection();
            Statement statement = statementHandler.prepare(connection);
            statementHandler.parameterize(statement);
            return statementHandler.query(statement);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
